<template>
  <div>
    <a-card :bordered="false" style="margin-top: 24px; min-height: 45vh">
      <a-tabs default-active-key="1" @change="tabChange" :animated="false">
        <a-tab-pane key="1" tab="分享码生成" forceRender>
          <div class="head">
            <a-button type="primary" @click="getShareCode">生成分享码</a-button>
            <a-button @click="downLoad" :disabled="disabledBtn">全部下载</a-button>
          </div>
          <div class="shareInfo" v-if="shareInfo">{{ shareInfo.shareRoleName }},{{ shareInfo.brandName }},{{ shareInfo.shareTypeName }}</div>
          <div class="ant-pro-pages-list-projects-cardList">
            <a-list style="margin-top: 24px" :loading="loading" :data-source="codeList" :grid="{ gutter: 0 }">
              <a-list-item slot="renderItem" slot-scope="item, index" :key="index" @click="handleCard(item)">
                <product :item="item" :isAdd="false" :type="shareInfo.shareType == 1 ? 'theme' : 'product'"></product>
              </a-list-item>
            </a-list>
          </div>
          <!-- <div class="pagination" v-if="codeList.length > 0">
            <a-pagination show-size-changer show-quick-jumper :default-current="codeCurrentPage" :total="codeTotal" @change="onChangeCode" @showSizeChange="onShowSizeChange" defaultPageSize="20"/>
          </div> -->
        </a-tab-pane>
        <a-tab-pane key="2" tab="分享角色">
          <a-button type="primary" @click="editRole('add')" class="addRole">新增角色</a-button>
          <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="pagination" :scroll="{ x: 1300 }">
            <span slot="action" slot-scope="text, record">
              <a @click="editRole(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除吗？" @confirm="deleteRole(record.id)">
                <a-icon slot="icon" type="question-circle-o" style="color: red" />
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </span>
          </s-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <roleModal ref="roleModal" @restOk="restOk"></roleModal>
    <selectGoods ref="selectGoods" @creatPoster="shareRequest" :weid="weid"></selectGoods>
    <selectMaterial ref="selectMaterial" @creatPoster="shareRequest" :weid="weid"></selectMaterial>
    <a-modal title="提示" :visible="visibleTip" @ok="visibleTip = false" @cancel="visibleTip = false">
      <p style="fontsize: 16px">请先生成分享码</p>
    </a-modal>
    <shareInfoModal ref="shareInfoModal" @createShareRequest="createShareRequest"></shareInfoModal>
    <a-modal title="加载" :visible="visibleLoading" @cancel="cancelCreate" :closable="false" :maskClosable="false">
      <div style="display: flex">
        <p style="fontsize: 16px; margin-right: 20px">正在生成海报，请勿退出</p>
        <a-spin size="large" />
      </div>
      <template slot="footer">
        <a-button @click="cancelCreate">取消</a-button>
      </template>
    </a-modal>
    <a-modal title="下载" :visible="visibleDownLoading" @cancel="cancelDownLoading" :closable="false" :maskClosable="false">
      <div style="display: flex">
        <p style="fontsize: 16px; margin-right: 20px">正在打包下载文件</p>
        <a-spin size="large" />
      </div>
      <template slot="footer">
        <a-button @click="cancelDownLoading">取消</a-button>
      </template>
    </a-modal>
    <a-modal title="选择下载内容类型" :visible="visibleDownType" @ok="downConfirm" @cancel="cancelDown">
      <a-form-model :model="downForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item>
          <a-checkbox-group @change="onChange" v-model="downForm.posterType">
            <a-row v-for="item in downTypeList" :key="item.value" style="margin-top: 12px">
              <a-col :span="24">
                <a-checkbox :value="item.value"> {{ item.label }} </a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { STable } from '@/views/box/components'
import roleModal from '@/views/pos+/activityConfiguration/components/roleModal'
import shareInfoModal from '@/views/pos+/activityConfiguration/components/shareInfoModal'
import product from '@/views/pos+/activityConfiguration/components/product'
import selectGoods from '@/views/pos+/activityConfiguration/components/selectGoods'
import selectMaterial from '@/views/pos+/activityConfiguration/components/selectMaterial'
import { shareRoleList, deleteRole, themeDetail, themeList, searchProduct, creatPoster, searchSharePoster, downPoster, creatShare } from '@/api/pos/shareCode.js'
const columns = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '角色名',
    dataIndex: 'name'
  },
  {
    title: '创建人',
    dataIndex: 'operatorName'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },

  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      columns,
      currentTab: 1,
      codeList: [],
      codeCurrentPage: 1,
      codeTotal: 0,
      codeTotalPages: 0,
      codePageSize: 20,
      loading: false,
      shareInfo: '', // 分享详情
      visibleTip: false, // 下载提示
      visibleLoading: false, // 加载
      downTypeList: [],
      visibleDownType: false,
      visibleDownLoading: false,
      shareType: '',
      weid: '',
      createShareInfo: '', // 创建素材分享
      disabledBtn: false,
      downForm: {posterType:[]},
      // 角色
      roleList: [],
      roleCurrentPage: 1,
      roleTotal: 0,
      roleTotalPages: 0,
      rolePageSize: 10,

      pagination: {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      loadData: parameter => {
        const obj = {
          current: parameter.pageNo,
          size: parameter.pageSize
        }
        return shareRoleList(obj).then(res => {
          if (res.code === 200) {
            this.pagination.current = res.data.current
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                pageNo: 0,
                count: 0,
                pageSize: 10
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  components: {
    product,
    STable,
    roleModal,
    selectGoods,
    shareInfoModal,
    selectMaterial
  },
  created() {
    this.loading = true
    this.getShareInfo()
  },
  mounted() {},
  methods: {
    // 下载
    async downLoadRequest() {
      this.disabledBtn = true
      const that = this
      const obj = {
        posterType: this.downForm.posterType,
        roleId: this.shareInfo.shareRoleId,
        shareId: this.shareInfo.id
      }
      const res = await downPoster(obj)
      if (res.code == 200) {
        this.redisKey = res.data
        this.downForm = {posterType: []}
        this.searchDownInterval = setInterval(() => {
          that.getSharePoster(1, 'down')
        }, 5000)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 取消下载
    cancelDown() {
      this.downForm = {posterType: []}
      this.visibleDownType = false
    },
    // 下载确定
    downConfirm() {
      if (this.downForm.posterType.length == 0) {
        this.$message.warning('请至少选择一个下载类型')
        return
      }
      this.visibleDownType = false
      this.visibleDownLoading = true
      this.downLoadRequest()
    },
    onChange() {},
    // 弹框参数
    createShareRequest(val) {
      const that = this
      this.createShareInfo = val
      this.shareType = val.type
      this.weid = val.brand
      this.$nextTick(() => {
        if (val.type == 1) {
          that.$refs.selectMaterial.show()
        } else {
          that.$refs.selectGoods.show()
        }
      })
    },
    // 创建素材分享参数
    async shareRequest(arr) {
      let obj = {
        shareRoleId: this.createShareInfo.role,
        brandId: this.createShareInfo.brand,
        shareType: this.createShareInfo.type,
        operatorId: this.$store.getters.userInfo.workNo,
        operatorName: this.$store.getters.userInfo.realname
      }
      const res = await creatShare(obj)
      if (res.code == 200) {
        this.shareKey = res.data
        this.creatPosterRequest(arr)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 生成海报
    async creatPosterRequest(arr) {
      const that = this
      const obj = {
        detailIds: arr,
        shareId: this.shareKey
      }
      const res = await creatPoster(obj)
      if (res.code == 200) {
        console.log('==生成海报==', res.data)
        if (this.shareType == 1) {
          this.$refs.selectMaterial.close()
        } else {
          this.$refs.selectGoods.close()
        }
        this.redisKey = res.data
        this.visibleLoading = true
        this.searchInterval = setInterval(() => {
          that.getSharePoster(1, 'created')
        }, 5000)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 取消生成
    cancelCreate() {
      this.visibleLoading = false
      if (this.searchInterval) {
        clearInterval(this.searchInterval)
      }
      // 中止
      this.getSharePoster(2, 'created')
    },
    // 轮询
    async getSharePoster(type, val) {
      const obj = {
        redisKey: this.redisKey,
        type: type
      }
      const res = await searchSharePoster(obj)
      if (res.code == 200) {
        if (val == 'created') {
          // 生成
          if (res.data == 'FINISH') {
            this.visibleLoading = false
            clearInterval(this.searchInterval)
            this.$message.success('分享码生成成功')
            this.loading = true
            this.getShareInfo()
          } else if (res.data == 'STOP') {
            // 中止
            this.loading = true
            this.getShareInfo()
          }
        } else {
          // 下载
          let ret = JSON.parse(res.data)
          if (ret.code == 'FINISH') {
            window.open(ret.result, '分享码')
            this.$message.success('下载分享码生成成功')
            clearInterval(this.searchDownInterval)
            this.disabledBtn = false
            this.visibleDownLoading = false
          }
        }
      } else {
        this.visibleLoading = false
        this.$message.error(res.msg)
        if (this.searchInterval) {
          clearInterval(this.searchInterval)
        }
        if (this.searchDownInterval) {
          clearInterval(this.searchDownInterval)
        }
        this.disabledBtn = false
      }
    },
    // 全部下载
    downLoad() {
      if (this.codeList.length == 0) {
        this.visibleTip = true
        return
      }
      this.visibleDownType = true
      if (this.shareInfo.shareType == 1) {
        this.downTypeList = [
          { label: '素材标题和简介', value: 1 },
          { label: '视频/原图', value: 2 },
          { label: '海报', value: 3 },
          { label: '单品海报', value: 5 },
          { label: '太阳码', value: 4 }
        ]
      } else {
        this.downTypeList = [
          { label: '视频/原图', value: 2 },
          { label: '海报', value: 3 },
          { label: '太阳码', value: 4 }
        ]
      }
    },
    // 下载loading-取消
    cancelDownLoading() {
      this.disabledBtn = false
      this.visibleDownLoading = false
      clearInterval(this.searchDownInterval)
      this.downForm = {posterType: []}
    },
    // 点击卡片
    handleCard(val) {
      if (this.shareInfo.shareType == 1) {
        const a = this.$router.resolve({ path: `/pos+/activityConfiguration/shareCode/detail/${val.lookId}/${this.shareInfo.id}/${this.shareInfo.shareRoleId}` })
        window.open(a.href, '_blank')
      } else {
        const a = this.$router.resolve({ path: `/pos+/activityConfiguration/shareCode/productDetail/${val.id}/${this.shareInfo.id}/${this.shareInfo.shareRoleId}` })
        window.open(a.href, '_blank')
      }
    },
    // 查询素材分享参数详情
    async getShareInfo() {
      const obj = {
        operatorId: this.$store.getters.userInfo.workNo
      }
      const res = await themeDetail(obj)
      if (res.code == 200) {
        let result = res.data
        let resultStr = JSON.stringify(result)
        if (resultStr && resultStr != '{}') {
          this.shareInfo = result
          if (result.shareDetailIds.length > 0) {
            this.codeCurrentPage = 1
            this.getList(result)
          } else {
            this.loading = false
          }
        } else {
          this.loading = false
        }
      } else {
        this.$message.error(res.msg)
      }
      this.downForm = {posterType:[]}
    },
    // 生成分享码
    getShareCode() {
      this.$refs.shareInfoModal.show()
    },

    tabChange(e) {
      if (this.currentTab == e) {
        return
      }
      this.currentTab = e
      if (this.currentTab == 1) {
        this.getShareInfo()
      } else {
      }
    },
    onChangeCode(e) {
      this.codeCurrentPage = e
      this.getList(this.shareInfo)
    },
    onShowSizeChange(current, pageSize) {
      this.codeCurrentPage = current
      this.codePageSize = pageSize
      this.getList(this.shareInfo)
    },
    // 创建、编辑
    editRole(val) {
      this.$refs.roleModal.show(val)
    },
    // 创建、编辑成功
    restOk() {
      //   this.loadData()
      this.$refs.table.refresh()
    },
    // 删除角色
    async deleteRole(id) {
      let obj = {
        id: id
      }
      const res = await deleteRole(obj)
      if (res.code == 200) {
        this.$message.success(res.msg)
        // this.loadData()
        this.$refs.table.refresh()
      } else {
        this.$message.error(res.msg)
      }
    },

    // 获取生成码列表
    async getList(val) {
      if (this.shareInfo.shareType == 1) {
        // 素材
        const obj = {
          lookIdList: this.shareInfo.shareDetailIds,
          mallBrandId: val.brandId,
          // current: this.codeCurrentPage,
          // size: this.codePageSize
          current: 1,
          size: this.shareInfo.shareDetailIds.length
        }
        const res = await themeList(obj)
        this.loading = false
        if (res.code == 200) {
          let result = res.data
          this.codeCurrentPage = result.current
          this.codeTotal = result.total
          this.codeTotalPages = parseInt(result.total / result.size) + 1
          const dataList = result.records.map(item => {
            const iconLoading = false
            return {
              ...item,
              iconLoading
            }
          })
          this.codeList = dataList
        } else {
          this.$message.error(res.msg)
        }
      } else {
        // 商品
        const d = {
          includeProductIds: this.shareInfo.shareDetailIds,
          weid: val.brandId
        }
        const data = {
          page: {
            pageNo: this.codeCurrentPage,
            pageSize: this.codePageSize
          },
          requestData: d
        }
        const res = await searchProduct(data)
        this.loading = false
        if (res.code == 0) {
          let result = res.page
          this.codeCurrentPage = result.pageNo
          this.codeTotal = result.count
          this.codeTotalPages = result.pages
          const dataList = res.data.map(item => {
            const iconLoading = false
            return {
              ...item,
              iconLoading
            }
          })
          this.codeList = dataList
          console.log('===商品列表===', this.codeList)
        } else {
          this.$message.error(res.msg)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.head {
  display: flex;
  justify-content: space-between;
}
.shareInfo {
  margin-top: 12px;
  font-weight: 700;
  font-style: normal;
  font-size: 18px;
  color: #333;
}
.ant-pro-pages-list-projects-cardList {
  height: 100%;
  min-height: 200px;
  overflow-y: auto;
  /deep/ .ant-row {
    display: grid;
    justify-content: space-evenly;
    grid-template-columns: repeat(auto-fill, 172px);
    // grid-row-gap: 16px;
    grid-column-gap: 8px;
  }
  /deep/ .ant-row::before {
    content: '';
    width: 0;
    display: none;
  }

  /deep/ .ant-list-item {
    // margin-bottom: 20px;
    .ant-card-hoverable {
      cursor: default;
    }
  }
  /deep/ .ant-card {
    width: 172px;
    position: relative;
    overflow: hidden;
    padding: 12px;
  }
  /deep/ .ant-card-hoverable:hover {
    border: 1px solid #1890ff;
    box-shadow: 0 2px 8px rgb(0 0 0 / 30%);
  }
  /deep/ .ant-card-meta-title {
    margin-bottom: 4px;
  }
  /deep/ .ant-card-meta-description {
    height: 44px;
    overflow: hidden;
    line-height: 22px;
  }
  /deep/ .ant-card-cover {
    width: 140px;
    height: 140px;
    margin: 0 auto;
    background: #fff;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
      object-fit: scale-down;
      border-radius: 4px;
    }
  }
  /deep/ .ant-card-body {
    padding: 0;
    position: relative;
    > p {
      margin-top: -30px;
      background: rgba(0, 0, 0, 0.4);
      line-height: 20px;
      color: #fff;
      text-align: center;
      font-size: 12px;
      border-radius: 0 0 4px 4px;
    }
  }
  .cardItemContent {
    padding: 0px 0px 6px;
    line-height: 20px;
    font-family: PingFangSC-Regular, PingFang SC;
    > p {
      color: #cdcdcd;
      font-size: 12px;
      line-height: 16px;
      margin-bottom: 0;
    }
    > h3 {
      font-size: 16px;
      line-height: 28px;
      margin-bottom: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      .topping {
        height: 22px;
        border-radius: 2px;
        border: 1px solid #1890ff;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #1890ff;
        line-height: 22px;
        padding: 0 4px;
        margin-right: 4px;
        display: block;
        float: left;
        margin-top: 3px;
      }
    }

    .red {
      color: #f45555;
      font-size: 14px;
      line-height: 26px;
    }
    .origin {
      font-size: 12px;

      font-weight: 400;
      color: #8c8c8c;
      line-height: 26px;
    }
    .blue {
      color: #1890ff;
    }
    /deep/ .ant-pro-avatar-list {
      flex: 0 1 auto;
    }
    /deep/.ant-skeleton-title {
      margin-top: 0;
      margin-bottom: 0;
    }
  }
  .btn {
    position: absolute;
    bottom: 4px;
    height: 24px;
    width: 148px;
    button {
      height: 24px;
      border-radius: 6px;
    }
    button:active {
      transform: scale(0.9);
    }
  }
  /deep/ .ant-list-pagination {
    margin-top: 0;
  }
}
.pagination {
  float: right;
}
.addRole {
  margin-bottom: 24px;
}
</style>

